import { Button, Input, message } from "antd";
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { setNameToken } from "../../store/authSlice";
import { userApi } from "../../api/user";
import { Encrypt } from "../../utils/secret";

export default function Login() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [messageApi, contextHolder] = message.useMessage();
  const [username, setUsername] = useState("");
  const [pwd, setPwd] = useState("");

  async function handleLogin() {
    if (!username.trim() || !pwd.trim()) {
      messageApi.warning("请输入用户名或密码");
      return;
    }
    const res = await userApi.login({ name: username, password: Encrypt(pwd) });

    dispatch(setNameToken({ name: username, token: res.token ?? "" })); // 使用重命名后的 action
    message.success(`欢迎, ${username}!`);
    navigate("/app/home");
  }

  return (
    <>
      {contextHolder}
      <div style={{ maxWidth: 400, margin: "0 auto", padding: 24 }}>
        <h1 style={{ textAlign: "center", marginBottom: 24 }}>登录页</h1>
        <Input
          placeholder="请输入用户名"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          style={{ marginBottom: 16 }}
        />
        <Input
          placeholder="请输入密码"
          type="password"
          value={pwd}
          onChange={(e) => setPwd(e.target.value)}
          onPressEnter={handleLogin}
          style={{ marginBottom: 16 }}
        />
        <Button type="primary" onClick={handleLogin} block>
          登录
        </Button>
      </div>
    </>
  );
}
